import { ArrowLeftOutlined, EditOutlined } from "@ant-design/icons/lib/icons";
import { Button, Typography, Space, Input, message } from "antd";
import { FC, useEffect, useState } from "react";
import { useNavigate, useParams } from "react-router-dom";
import EditToolbar from "./EditToolbar";
import useGetPageInfo from "@/hooks/useGetPageInfo";
import { changePageTitle } from "@/store/pageInfoReducer";
import { useDispatch } from "react-redux";
import useGetComponentInfo from "@/hooks/useGetComponentInfo";
import { useDebounceEffect, useKeyPress, useRequest } from "ahooks";
import { updateQuestionService } from "@/services/question";
import { QUESTION_STAT_PATHNAME } from "@/router";

const { Title } = Typography;

//保存按钮组件
const SaveButton: FC = () => {
  const { componentList = [] } = useGetComponentInfo();
  const pageInfo = useGetPageInfo();
  const { id } = useParams();
  const { loading, run: save } = useRequest(
    async () => {
      await updateQuestionService(Number(id), {
        ...pageInfo,
        componentList,
      });
    },
    { manual: true }
  );

  useKeyPress(
    ["ctrl.s", "meta.s", "ctrl.enter", "meta.enter"],
    (e: KeyboardEvent) => {
      e.preventDefault();
      if (loading) return;
      save();
    }
  );
  const [enableAutoSave, setEnableAutoSave] = useState(false);

  // 延迟启用自动保存
  useEffect(() => {
    const timer = setTimeout(() => {
      setEnableAutoSave(true);
    }, 3000); // 2秒后启用自动保存

    return () => clearTimeout(timer);
  }, []);

  //自动保存 防抖
  useDebounceEffect(
    () => {
      if (loading || !enableAutoSave) return; // 添加初始化检查

      save();
    },
    [componentList, pageInfo],
    {
      wait: 1000,
    }
  );

  return (
    <Button loading={loading} onClick={save}>
      保存
    </Button>
  );
};

//发布按钮组件
const PublishButton: FC = () => {
  const nav = useNavigate();
  const { componentList = [] } = useGetComponentInfo();
  const pageInfo = useGetPageInfo();
  const { id } = useParams();
  const { loading, run: pub } = useRequest(
    async () => {
      await updateQuestionService(Number(id), {
        ...pageInfo,
        componentList,
        isPublished: true,
      });
    },
    {
      manual: true,
      onSuccess() {
        message.success("发布成功");
        nav(QUESTION_STAT_PATHNAME + "/" + id);
      },
    }
  );

  return (
    <Button type="primary" loading={loading} onClick={pub}>
      发布
    </Button>
  );
};

//标题组件
const TitleElement: FC = () => {
  const { title } = useGetPageInfo();

  const dispatch = useDispatch();

  const [editState, setEditState] = useState(false);

  if (!title) return;

  if (editState) {
    return (
      <Input
        value={title}
        onBlur={() => setEditState(false)}
        onPressEnter={() => setEditState(false)}
        onChange={(e) => dispatch(changePageTitle(e.target.value))}
      />
    );
  }

  return (
    <Space>
      <Title level={5} className="!mb-0 !text-base">
        {title}
      </Title>
      <Button
        type="text"
        icon={<EditOutlined />}
        onClick={() => setEditState(true)}
      ></Button>
    </Space>
  );
};

const EditHeader: FC = () => {
  const nav = useNavigate();
  return (
    <div className="bg-white border-[#e8e8e8] border-1 px-3">
      <div className="flex  my-2">
        <div className="flex-1  ">
          <Space>
            <Button
              type="link"
              icon={<ArrowLeftOutlined />}
              onClick={() => nav(-1)}
            >
              返回
            </Button>
            <TitleElement />
          </Space>
        </div>
        <div className="flex-1 text-center">
          <EditToolbar />
        </div>
        <div className="flex-1 text-right">
          <Space>
            <SaveButton />
            <PublishButton />
          </Space>
        </div>
      </div>
    </div>
  );
};

export default EditHeader;
